using Microsoft.AspNetCore.Mvc;
using RAGApp.Api.Models;
using RAGApp.Api.Models.DTOs;
using RAGApp.Api.Services.Interfaces;

namespace RAGApp.Api.Controllers;

[ApiController]
[Route("api/[controller]")]
public class ChatController : ControllerBase
{
    private readonly IChatService _chatService;
    private readonly ILogger<ChatController> _logger;

    public ChatController(IChatService chatService, ILogger<ChatController> logger)
    {
        _chatService = chatService;
        _logger = logger;
    }

    [HttpPost]
    public async Task<ActionResult<ChatResponseDto>> Chat([FromBody] ChatRequestDto request)
    {
        try
        {
            var response = await _chatService.GetAnswerAsync(request);
            return Ok(response);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "处理聊天请求时发生错误");
            return StatusCode(500, "处理聊天请求时发生错误");
        }
    }

    [HttpGet("conversation/{id}")]
    public async Task<ActionResult<List<Message>>> GetConversationHistory(Guid id)
    {
        try
        {
            var history = await _chatService.GetConversationHistoryAsync(id);
            return Ok(history);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "获取对话历史时发生错误");
            return StatusCode(500, "获取对话历史时发生错误");
        }
    }

    [HttpPost("conversation")]
    public async Task<ActionResult<Conversation>> CreateConversation()
    {
        try
        {
            var conversation = await _chatService.CreateConversationAsync();
            return Ok(conversation);
        }
        catch (Exception ex)
        {
            _logger.LogError(ex, "创建对话时发生错误");
            return StatusCode(500, "创建对话时发生错误");
        }
    }
} 